package com.lihonghao.proxy;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class OuterProxyServer {
    private static final String INNER_SERVER_IP = "192.168.1.9"; // 内网服务器IP
    private static final int INNER_SERVER_PORT = 8080; // 内网服务器端口
    private static final int OUTER_PROXY_PORT = 9090; // 外网代理服务器端口

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                  .channel(NioServerSocketChannel.class)
                  .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new OuterProxyHandler());
                        }
                    });

            ChannelFuture serverFuture = serverBootstrap.bind(OUTER_PROXY_PORT).sync();
            System.out.println("外网代理服务器已启动，监听端口 " + OUTER_PROXY_PORT);
            serverFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    static class OuterProxyHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext outerCtx, Object msg) throws Exception {
            String request = (String) msg;
            System.out.println("外网代理服务器接收到请求: " + request);

            Bootstrap bootstrap = new Bootstrap();
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                bootstrap.group(group)
                      .channel(NioSocketChannel.class)
                      .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new StringDecoder());
                                ch.pipeline().addLast(new StringEncoder());
                                ch.pipeline().addLast(new InnerServerForwardHandler(outerCtx));
                            }
                        });

                ChannelFuture future = bootstrap.connect(INNER_SERVER_IP, INNER_SERVER_PORT).sync();
                future.channel().writeAndFlush(request).sync();
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        }
    }

    static class InnerServerForwardHandler extends ChannelInboundHandlerAdapter {
        private final ChannelHandlerContext outerCtx;

        public InnerServerForwardHandler(ChannelHandlerContext outerCtx) {
            this.outerCtx = outerCtx;
        }

        @Override
        public void channelRead(ChannelHandlerContext innerCtx, Object msg) throws Exception {
            String response = (String) msg;
            System.out.println("外网代理服务器接收到内网服务器响应: " + response);
            outerCtx.writeAndFlush(response).sync();
        }
    }
}